<?php
// +----------------------------------------------------------------------
// | 基础模型
// +----------------------------------------------------------------------
// | Author: myh
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;

class BaseModel extends Model
{   
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    //插入前
    public static function onBeforeInsert($data){
        return $data['creator'] = getUserId();
    }

    //更新前
    public static function onBeforeUpdate($data){
        return $data['updator'] = getUserId();
    }

    //分页查询
    public static function page($param, $other = []){
        //分页默认值
        $page = !isset($param['page']) ? 1 : $param['page'];
        $pageSize = !isset($param['page_size']) || $param['page_size'] > 100 ? 10 : $param['page_size'];

        
        //设置排序
        if(isset($other['order']) && $other['order']){
            $arr = explode(',',$other['order']);
            $orderField = $arr[0];
            $orderValue = $arr[1];
        }else{
            $orderField = "id";
            $orderValue = "desc";
        }

        unset($param['page']);
        unset($param['pageSize']);
        $keyArr = array_keys($param);
        $query = self::withSearch($keyArr,$param);
        
        $data['total'] = $query->count();
        $data['list'] = [];
        if($data['total'] > 0){
            //设置排除字段
            if(isset($other['withoutField']) && $other['withoutField']){
                $query = $query->withoutField($other['withoutField']);
            }
            //设置查询的字段
            if(isset($other['field']) && $other['field']){
                $query = $query->field($other['field']);
            }

            $data['list'] = $query->order($orderField,$orderValue)->limit(($page-1)*$pageSize,$pageSize)->select()->toArray();
        }

        return $data;
    }

    /**
     * 删除
     * @param  string|array  $ids     需要删除数据的id
     */
    public static function deleteById($ids){
        if(!empty($ids)){
            if (!is_array($ids)) {
                $ids = explode(',',$ids);
            }
            
            foreach($ids as $id){
                $model = self::find($id);
                $model->delete_time = date('Y-m-d H:i:s',time());
                $model->save();
            }
        }
    }

}
